package com.dalongxin.work.page;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.TextView;

import com.dalongxin.work.Constants;
import com.dalongxin.work.EventCenter;
import com.dalongxin.work.R;
import com.dalongxin.work.data.Contact;
import com.dalongxin.work.data.DjHtps;
import com.dalongxin.work.data.Project;
import com.dalongxin.work.data.Supplier;
import com.dalongxin.work.utils.HttpUtil;
import com.dalongxin.work.utils.StatusBarUtil;
import com.dalongxin.work.utils.ToastUtil;
import com.dalongxin.work.view.MyCommonDialog;
import com.dalongxin.work.view.MyCommonEditDialog;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 新建合同评审
 */
@ContentView(R.layout.activity_dj_new_htps)
public class DjHtpsNewActivity extends BaseActivity implements View.OnClickListener {

    @ViewInject(R.id.tool_bar)
    private Toolbar toolbar;
    @ViewInject(R.id.title_back)
    private ImageButton titleBack;
    @ViewInject(R.id.title_text)
    private TextView titleText;
    @ViewInject(R.id.submit)
    private TextView submit;

    @ViewInject(R.id.tv_choose_fbr)
    private TextView tvChooseFbr;//选择发表人
    @ViewInject(R.id.tv_choose_hybshr)
    private TextView tvChooseHybshr;//选择合约部审核人
    @ViewInject(R.id.tv_choose_xmbshr)
    private TextView tvChooseXmbshr;//选择项目部审核人
    @ViewInject(R.id.tv_choose_nsbshr)
    private TextView tvChooseNsbshr;//选择内审部审核人
    @ViewInject(R.id.tv_choose_zjl)
    private TextView tvChooseZjl;//选择总经理
    @ViewInject(R.id.tv_choose_psjsrq)
    private TextView tvChoosePsjsrq;//评审结束日期
    @ViewInject(R.id.tv_choose_sqrq)
    private TextView tvChooseSqrq;//申请日期
    @ViewInject(R.id.tv_choose_xm)
    private TextView tvChooseXm;//选择项目
    @ViewInject(R.id.tv_choose_gys)
    private TextView tvChooseGys;//选择供应商

    @ViewInject(R.id.et_htzynr)
    private EditText etHtzynr;//合同主要内容
    @ViewInject(R.id.et_htmc)
    private EditText etHtmc;//合同名称
    @ViewInject(R.id.et_htbh)
    private EditText etHtbh;//合同编号
    @ViewInject(R.id.btn_operate)
    private Button btnOperate;

    public static final int REQ_CHOOSE_CONTACT_Fbr = 1001;
    public static final int REQ_CHOOSE_CONTACT_Hybshr = 1002;
    public static final int REQ_CHOOSE_CONTACT_Xmbshr = 1003;
    public static final int REQ_CHOOSE_CONTACT_Nsbshr = 1004;
    public static final int REQ_CHOOSE_CONTACT_Zjl = 1005;
    public static final int REQ_CHOOSE_XM = 1006;
    public static final int REQ_CHOOSE_GYS = 1007;
    public Calendar calendar;

    private Contact chooseFbr;
    private Contact chooseHybshr;
    private Contact chooseXmbshr;
    private Contact chooseNsbshr;
    private Contact chooseZjl;
    private String psjsrq;
    private String sqrq;
    private Project chooseProject;
    private Supplier chooseSupplier;

    private String htzynr;
    private String htmc;
    private String htbh;

    private MyCommonDialog commonDialog;
    private MyCommonEditDialog commonEditDialog;

    public static final String IS_EDIT = "is_edit";
    private int isEdit = 0;// 0新建 1查看
    private DjHtps bean;
    private boolean canEdit = false;
    private int editState = 0;//0查看状态 1修改状态

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        //this.setSupportActionBar(toolbar);//这样menu才能显示出来【自定义toolbar的话 这个不要设置】
        //getSupportActionBar().setDisplayShowTitleEnabled(false);//去掉默认title的显示
        StatusBarUtil.setPaddingSmart(this, toolbar);
        StatusBarUtil.darkMode(this, false);
        isEdit = getIntent().getIntExtra(IS_EDIT, 0);
        if(isEdit == 0) {
            titleText.setText("新建合同评审");
            submit.setText("提交");
            switchToEditState();
        }else {
            Bundle bundle = getIntent().getBundleExtra("bundle");
            bean = (DjHtps) bundle.getSerializable("BEAN");
            if(bean == null) {
                finish();
                return;
            }
            if(bean.getCreateId() == getDefaultAccount().getId() && bean.getStatus() == 0) {
                canEdit = true;
                titleText.setText("查看合同评审");
                submit.setText("修改");
            }else {
                titleText.setText("查看合同评审");
                submit.setVisibility(View.GONE);
            }
            fillDataToPage(bean);
            btnOperate.setVisibility(showOperateBtn(bean) ? View.VISIBLE : View.GONE);
            btnOperate.setOnClickListener(this);
        }
        titleBack.setOnClickListener(this);
        submit.setOnClickListener(this);

        calendar = Calendar.getInstance();
    }

    private boolean showOperateBtn(DjHtps bean) {
        if(bean.getStatus() == 0 && bean.getApproveId1() == getDefaultAccount().getId()) {
            return true;
        }
        if(bean.getStatus() == 1 && bean.getApproveId2() == getDefaultAccount().getId()) {
            return true;
        }
        if(bean.getStatus() == 2 && bean.getApproveId3() == getDefaultAccount().getId()) {
            return true;
        }
        if(bean.getStatus() == 3 && bean.getApproveId4() == getDefaultAccount().getId()) {
            return true;
        }
        return false;
    }

    private void fillDataToPage(DjHtps bean) {
        chooseFbr = new Contact();
        chooseFbr.setId(bean.getApplyUserId());
        chooseFbr.setUserName(bean.getApplyUserName());
        chooseHybshr = new Contact();
        chooseHybshr.setId(bean.getApproveId1());
        chooseHybshr.setUserName(bean.getApproveName1());
        chooseXmbshr = new Contact();
        chooseXmbshr.setId(bean.getApproveId2());
        chooseXmbshr.setUserName(bean.getApproveName2());
        chooseNsbshr = new Contact();
        chooseNsbshr.setId(bean.getApproveId3());
        chooseNsbshr.setUserName(bean.getApproveName3());
        chooseZjl = new Contact();
        chooseZjl.setId(bean.getApproveId4());
        chooseZjl.setUserName(bean.getApproveName4());

        chooseProject = new Project();
        chooseProject.setId(bean.getProjectId());
        chooseProject.setName(bean.getProjectName());
        chooseSupplier = new Supplier();
        chooseSupplier.setId(bean.getSupplierId());
        chooseSupplier.setName(bean.getSupplierName());

        sqrq = bean.getFillDate();
        psjsrq = bean.getEndDate();
        htmc = bean.getContractName();
        htbh = bean.getContractNumber();
        htzynr = bean.getContent();

        tvChooseFbr.setText(chooseFbr.getUserName());
        tvChooseHybshr.setText(chooseHybshr.getUserName());
        tvChooseXmbshr.setText(chooseXmbshr.getUserName());
        tvChooseNsbshr.setText(chooseNsbshr.getUserName());
        tvChooseZjl.setText(chooseZjl.getUserName());
        tvChooseXm.setText(chooseProject.getName());
        tvChooseGys.setText(chooseSupplier.getName());
        tvChooseSqrq.setText(sqrq);
        tvChoosePsjsrq.setText(psjsrq);

        etHtmc.setText(htmc);
        etHtbh.setText(htbh);
        etHtzynr.setText(htzynr);

        switchToViewState();//默认查看状态
    }

    private void switchToEditState() {
        tvChooseFbr.setOnClickListener(this);
        tvChooseHybshr.setOnClickListener(this);
        tvChooseXmbshr.setOnClickListener(this);
        tvChooseNsbshr.setOnClickListener(this);
        tvChooseZjl.setOnClickListener(this);
        tvChoosePsjsrq.setOnClickListener(this);
        tvChooseSqrq.setOnClickListener(this);
        tvChooseXm.setOnClickListener(this);
        tvChooseGys.setOnClickListener(this);
        etHtmc.setEnabled(true);
        etHtbh.setEnabled(true);
        etHtzynr.setEnabled(true);
    }

    private void switchToViewState() {
        tvChooseFbr.setOnClickListener(null);
        tvChooseHybshr.setOnClickListener(null);
        tvChooseXmbshr.setOnClickListener(null);
        tvChooseNsbshr.setOnClickListener(null);
        tvChooseZjl.setOnClickListener(null);
        tvChoosePsjsrq.setOnClickListener(null);
        tvChooseSqrq.setOnClickListener(null);
        tvChooseXm.setOnClickListener(null);
        tvChooseGys.setOnClickListener(null);
        etHtmc.setEnabled(false);
        etHtbh.setEnabled(false);
        etHtzynr.setEnabled(false);
    }

    private void submitHtps() {
        showLoading();
        Map<String, String> params = new HashMap<>();
        params.put("applyUserId", String.valueOf(chooseFbr.getId()));
        params.put("approveId1", String.valueOf(chooseHybshr.getId()));
        params.put("approveId2",String.valueOf(chooseXmbshr.getId()));
        params.put("approveId3",String.valueOf(chooseNsbshr.getId()));
        params.put("approveId4",String.valueOf(chooseZjl.getId()));
        params.put("content", htzynr);
        params.put("contractName", htmc);
        params.put("contractNumber", htbh);
        params.put("endDate", psjsrq);
        params.put("fillDate", sqrq);
        params.put("projectId", String.valueOf(chooseProject.getId()));
        params.put("supplierId", String.valueOf(chooseSupplier.getId()));
        if(canEdit) {
            params.put("id", String.valueOf(bean.getId()));
        }else {
            params.put("id", String.valueOf(0));
        }
        HttpUtil.getInstance().post(true, Constants.url_saveReview, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtil.e("response=" + response);
                if (response.optInt("ret") == 0) {
                    ToastUtil.showShort("提交成功");
                    EventBus.getDefault().post(EventCenter.call(EventCenter.HTPS_REFRESH));
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
                finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtil.showShort("服务器返回失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideLoading();
            }
        });
    }

    private void submitApprove(String content, int result) {
        showLoading();
        Map<String, String> params = new HashMap<>();
        params.put("msg", content);
        params.put("result", String.valueOf(result));
        params.put("id", String.valueOf(bean.getId()));
        HttpUtil.getInstance().post(true, Constants.url_approveReview, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                commonEditDialog.dismiss();
                LogUtil.e("response=" + response);
                if (response.optInt("ret") == 0) {
                    ToastUtil.showShort("提交成功");
                    EventBus.getDefault().post(EventCenter.call(EventCenter.HTPS_REFRESH));
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
                finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtil.showShort("服务器返回失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideLoading();
            }
        });
    }

    private void preSubmit() {
        if(tvChooseFbr == null) {
            ToastUtil.showShort("请选择发表人");
            return;
        }
        if(tvChooseHybshr == null) {
            ToastUtil.showShort("请选择合约部审核人");
            return;
        }
        if(tvChooseXmbshr == null) {
            ToastUtil.showShort("请选择项目部审核人");
            return;
        }
        if(tvChooseNsbshr == null) {
            ToastUtil.showShort("请选择内审部审核人");
            return;
        }
        if(tvChooseZjl == null) {
            ToastUtil.showShort("请选择总经理");
            return;
        }
        if(TextUtils.isEmpty(psjsrq)) {
            ToastUtil.showShort("请选择评审结束日期");
            return;
        }
        if(TextUtils.isEmpty(sqrq)) {
            ToastUtil.showShort("请选择申请日期");
            return;
        }
        if(chooseProject == null) {
            ToastUtil.showShort("请选择项目");
            return;
        }
        if(chooseSupplier == null) {
            ToastUtil.showShort("请选择供应商");
            return;
        }

        htzynr = etHtzynr.getText().toString();
        if(TextUtils.isEmpty(htzynr)) {
            ToastUtil.showShort("请填写合同主要内容");
            return;
        }
        htmc = etHtmc.getText().toString();
        if(TextUtils.isEmpty(htmc)) {
            ToastUtil.showShort("请填写合同名称");
            return;
        }
        htbh = etHtbh.getText().toString();
        if(TextUtils.isEmpty(htbh)) {
            ToastUtil.showShort("请填写合同编号");
            return;
        }
        commonDialog = new MyCommonDialog(this, "提示消息", "确定提交吗？", "检查一下","提交");
        commonDialog.setOkListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog != null && commonDialog.isShowing())
                    commonDialog.dismiss();
                submitHtps();
            }
        });
        commonDialog.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog != null && commonDialog.isShowing())
                    commonDialog.dismiss();
            }
        });
        commonDialog.show();
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.submit:
                if(isEdit == 0) {
                    preSubmit();
                }else {
                    if(canEdit) {
                        if (editState == 0) {
                            editState = 1;
                            titleText.setText("修改合同评审");
                            submit.setText("提交");
                            switchToEditState();
                        } else {
                            editState = 0;
                            titleText.setText("修改合同评审");
                            preSubmit();
                        }
                    }
                }
                break;
            case R.id.tv_choose_psjsrq:
                int year1 = calendar.get(Calendar.YEAR);
                int month1 = (calendar.get(Calendar.MONTH))+1;
                int day_of_month1 = calendar.get(Calendar.DAY_OF_MONTH);
                new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        psjsrq = String.format("%d-%d-%d",i,i1+1,i2);
                        tvChoosePsjsrq.setText(psjsrq);
                        tvChoosePsjsrq.setTextColor(getResources().getColor(R.color.black));
                    }
                },year1, month1, day_of_month1).show();
                break;
            case R.id.tv_choose_sqrq:
                int year2 = calendar.get(Calendar.YEAR);
                int month2 = (calendar.get(Calendar.MONTH))+1;
                int day_of_month2 = calendar.get(Calendar.DAY_OF_MONTH);
                new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        sqrq = String.format("%d-%d-%d",i,i1+1,i2);
                        tvChooseSqrq.setText(sqrq);
                        tvChooseSqrq.setTextColor(getResources().getColor(R.color.black));
                    }
                },year2, month2, day_of_month2).show();
                break;
            case R.id.tv_choose_fbr:
                intent = new Intent(this, ContactListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_CONTACT_Fbr);
                break;
            case R.id.tv_choose_hybshr:
                intent = new Intent(this, ContactListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_CONTACT_Hybshr);
                break;
            case R.id.tv_choose_xmbshr:
                intent = new Intent(this, ContactListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_CONTACT_Xmbshr);
                break;
            case R.id.tv_choose_nsbshr:
                intent = new Intent(this, ContactListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_CONTACT_Nsbshr);
                break;
            case R.id.tv_choose_zjl:
                intent = new Intent(this, ContactListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_CONTACT_Zjl);
                break;
            case R.id.tv_choose_xm:
                intent = new Intent(this, ProjectListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_XM);
                break;
            case R.id.tv_choose_gys:
                intent = new Intent(this, SupplierListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_GYS);
                break;
            case R.id.btn_operate:
                final MyCommonEditDialog.Builder builder2 = new MyCommonEditDialog.Builder(this);
                commonEditDialog = builder2.view(R.layout.dialog_approve).widthdp(300).heightdp(320).style(R.style.MyDialogStyle)
                        .addViewOnclick(R.id.cancel, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                commonEditDialog.dismiss();
                            }
                        }).addViewOnclick(R.id.ok, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                EditText etSpyj = (EditText)builder2.findViewById(R.id.et_spyj);
                                String spyj = etSpyj.getText().toString();
                                if(TextUtils.isEmpty(spyj)) {
                                    spyj = "";
                                }
                                RadioButton yes = (RadioButton)builder2.findViewById(R.id.radio_result_yes);
                                submitApprove(spyj, yes.isChecked() ? 0 : 1);
                            }
                        }).build();
                commonEditDialog.show();
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data == null)return;
        if(resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQ_CHOOSE_CONTACT_Fbr:
                    chooseFbr = (Contact)data.getSerializableExtra(ContactListActivity.DATA_CHOOSE_CONTACT);
                    tvChooseFbr.setText(chooseFbr.getUserName());
                    tvChooseFbr.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_CONTACT_Hybshr:
                    chooseHybshr = (Contact)data.getSerializableExtra(ContactListActivity.DATA_CHOOSE_CONTACT);
                    tvChooseHybshr.setText(chooseHybshr.getUserName());
                    tvChooseHybshr.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_CONTACT_Xmbshr:
                    chooseXmbshr = (Contact)data.getSerializableExtra(ContactListActivity.DATA_CHOOSE_CONTACT);
                    tvChooseXmbshr.setText(chooseXmbshr.getUserName());
                    tvChooseXmbshr.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_CONTACT_Nsbshr:
                    chooseNsbshr = (Contact)data.getSerializableExtra(ContactListActivity.DATA_CHOOSE_CONTACT);
                    tvChooseNsbshr.setText(chooseNsbshr.getUserName());
                    tvChooseNsbshr.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_CONTACT_Zjl:
                    chooseZjl = (Contact)data.getSerializableExtra(ContactListActivity.DATA_CHOOSE_CONTACT);
                    tvChooseZjl.setText(chooseZjl.getUserName());
                    tvChooseZjl.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_XM:
                    chooseProject = (Project)data.getSerializableExtra(ProjectListActivity.DATA_CHOOSE_XM);
                    tvChooseXm.setText(chooseProject.getName());
                    tvChooseXm.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_GYS:
                    chooseSupplier = (Supplier)data.getSerializableExtra(SupplierListActivity.DATA_CHOOSE_GYS);
                    tvChooseGys.setText(chooseSupplier.getName());
                    tvChooseGys.setTextColor(getResources().getColor(R.color.black));
                    break;
            }
        }
    }
}
